import getpath
import os
import logging
import myglobal
import config_json
import sample
import xlrd
import openpyxl
from mydb import MyDB_Base
import power
# fieldNames=["type","gg","t","d0","a0","b0","D0","S0","k","L0","Lu","du1","du2","Fm","Rm","FeH","ReH","FeL","ReL","ReL2","A","Z","At","Ae","Ag",'Agt',"屈强比","KN","MPa","MPa2","弹性模量","弹性模量2","备注"]
item_name_dict={
"Fm":"最大力(Fm)"
,"Rm":"抗拉强度(Rm)"
,"Ag":"最大力塑性延伸率(Ag)"
,"ReL":"下屈服强度(ReL)"
,"ReH":"上屈服强度(ReH)"
,"FRp0.2":"规定非比例延伸力(Fp0.2)"
,"Rp0.2":"规定非比例延伸强度(Rp0.2)"
,"Agt (corr.)":"Agt"
}
xy_dict={
# "du":(0,5),
# "S0":(0,5),
# "Lu":(0,5),
"Fm":(0,5),
"Rm":(0,5),
"Ag":(0,5),
"Agt (corr.)":(0,5),
"ReL":(0,5),
"ReH":(0,5),
"FRp0.2":(0,5),
"Rp0.2":(0,5),#type,num
"E":(0,5),
}
class SampleLashen(sample.Sample):
    def __init__(self):
        super().__init__()
        self.type="棒材"#试样类型
        self.gg=None#试样规格
        self.t=None#试验温度
        self.temp1=None
        self.temp2=None
        self.temp3=None
    def toLsClass(self):
        ls=power.ClassLS()
        ls.type=self.type
        for k  in self.items.keys():
            v=self.items[k]
            if k==("d0",""):
                ls.d0=v
            elif k==("a0",""):
                ls.a0=v
            elif k==("b0",""):
                ls.b0=v
            elif k==("D0",""):
                ls.D0=v
            elif k==("L0",""):
                ls.L0=v
            elif k==("Lu",""):
                ls.Lu=v
            elif k==("du",""):
                ls.du=v
            elif k==("Fm",""):
                ls.Fm=v
            elif k==("Rm",""):
                ls.Rm=v
            elif k==("FRp0.2",""):
                ls.Fp02=v
            elif k==("Rp0.2",""):
                ls.Rp02=v
            elif k==("FeH",""):
                ls.FeH=v
            elif k==("ReH",""):
                ls.ReH=v
            elif k==("FeL",""):
                ls.FeL=v
            elif k==("ReL",""):
                ls.ReL=v
            elif k==("E",""):
                ls.E=v
            elif k==("A",""):
                ls.A=v
            elif k==("Ag",""):
                ls.Ag=v
            elif k==("At",""):
                ls.At=v
        return ls
    def calc(self):
        # ls=power.ClassLS()
        # ls.fromItemsZWK(self)
        ls=self.toLsClass()
        ls.calc()
        setattr(self,"S0_",ls.S0)
def in_list(one, l1):
    for i in range(len(l1)):
        logging.info(str(one)+str(l1[i]))
        if one in l1[i]:
            return i
    return -1
def getdata(fname):
    logging.info(fname)
    xl_book = xlrd.open_workbook(fname)
    table = xl_book.sheets()[0]
    data = []
    for i in range(table.nrows):
        r = []
        for j in range(table.ncols):
            r.append(table.cell(i, j).value)
        data.append(r)
    print(data)
    samples = []
    at = 2
    while True:
        try:
            sample = {"items": [], "conc": []}
            sample["items"] = data[0][3:]
            for i in range(len(sample["items"])):
                sample["items"][i]=(sample["items"][i],"")
            sampleid = data[at][0]
            sample["sampleid"] = sampleid
            logging.info(sampleid)
            sample["conc"] = data[at][3:]
            print(sample)
            if sampleid == "":
                break
            samples.append(sample)
            at += 1
        except IndexError:
            break
    return samples
def test_getdata():
    fname=os.path.join(getpath.getpath(),"930.csv")
    data=getdata(fname)
    return data

def item_name(k):
    v=item_name_dict.get(k)
    if v==None:
        return k
    else:
        return v
def item_xy(k,value):
    r=xy_dict.get(k)
    logging.info([k,r])
    if r==None:
        return value
    else:
        xy1=power.Xy(r[0],r[1])
        return xy1.xiuyue(value)        
class MyDb(MyDB_Base):
    def __init__(self,mainw):
        super().__init__(mainw)
        self.doublefmt="%.03f"
        self.highT=False
        self.properties = [
            {"ele":None,"delegate":None,'width':130,'attr': "sampleid",'visible':True,  'header': "id"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "cailiao",'visible':True,  'header': "材料名称"},
            {"ele":None,"delegate":"comboEdit",'width':80,'attr': "type",'visible':True,  'header': "试样类型"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "gg",'visible':True,  'header': "试样规格"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "t",'visible':True,  'header': "试验温度"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
    def getDataDays(self, v):
        filename=config_json.setting['database']
        data=getdata(filename)
        return self.toObjects(data) 
    def resetProperties(self,items):
        self.properties = [
            {"ele":None,"delegate":None,'width':130,'attr': "sampleid",'visible':True,  'header': "id"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "cailiao",'visible':True,  'header': "材料名称"},
            {"ele":None,"delegate":"comboEdit",'width':80,'attr': "type",'visible':True,  'header': "试样类型"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "gg",'visible':True,  'header': "试样规格"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "t",'visible':True,  'header': "试验温度"},
        ]
        if self.highT:
            self.properties+=[{"ele":None,"delegate":"edit",'width':80,'attr': "temp1",'visible':True,  'header': "温度校准上"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "temp2",'visible':True,  'header': "温度校准中"},
            {"ele":None,"delegate":"edit",'width':80,'attr': "temp3",'visible':True,  'header': "温度校准下"}]
        self.properties.append({"ele":None,"delegate":"edit",'width':80,'attr': "beizhu",'visible':True,  'header': "备注"})
        for item in items:
            one={"edit":False,"ele":item,"delegate":"double",'width':80,'attr': item[0]+"_"+item[1],'visible':True,  'header': item[0]+" "+item[1]}
            self.properties.append(one)
    def toObjects(self,samples):        
        objs=[]
        num=0
        for one in samples:
            s=SampleLashen()
            s.num=num
            s.sampleid=one["sampleid"]
            # logging.info(s.sampleid)
            s.items={}
            logging.info(one["items"])
            for i in range(len(one["items"])): #one in one["items"]:
                s.items[one["items"][i]]=one["conc"][i]
            objs.append(s)
            num+=1
        self.resetProperties(s.items)
        return objs

    def items_to_attr(self):
        # k=one["items"][i]
        # v=one["conc"][i]
        # if k==("d0",""):
        #     s.d0=v
        # elif k==("L0",""):
        #     s.L0=v
        # elif k==("Lu",""):
        #     s.Lu=v
        # elif k==("du",""):
        #     s.du=v
        # elif k==("Fm",""):
        #     s.Fm=v
        # elif k==("Rm",""):
        #     s.Rm=v
        # elif k==("FRp0.2",""):
        #     s.Fp02=v
        # elif k==("Rp0.2",""):
        #     s.Rp02=v
        # elif k==("FeH",""):
        #     s.FeH=v
        # elif k==("ReH",""):
        #     s.ReH=v
        # elif k==("FeL",""):
        #     s.FeL=v
        # elif k==("ReL",""):
        #     s.ReL=v
        # elif k==("E",""):
        #     s.E=v
        # elif k==("A",""):
        #     s.A=v
        # elif k==("Ag",""):
        #     s.Ag=v
        # elif k==("At",""):
        #     s.At=v
        pass
    def calc(self):
        n=len(self.mainw.objects)
        for i in range(n):
            try:
                o=self.mainw.objects[i]
                o.calc()
            except ZeroDivisionError:
                pass  
        n=len(self.mainw.objects2)
        for i in range(n):
            try:
                o=self.mainw.objects2[i]
                o.calc()
            except ZeroDivisionError:
                pass        
    def output_xlsx(self, filepath):
        n = self.mainw.model2.rowCount()
        if n == 0:
            return
        filepath = filepath + ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        wb = openpyxl.Workbook()
        # 3. 构建列表头
        row = ["id","试样类型","备注"]
        for f in self.properties:
            if f["visible"] and f["ele"]!=None:
                row.append(item_name(f["ele"][0]))
        ws = wb.active
        ws.append(row)
        for row_idx in range(n):
            record = self.mainw.model2.getObjectRow(row_idx)
            row = [record.sampleid,record.type,record.beizhu]
            for f in self.properties:
                if f["visible"] and f["ele"]!=None:
                    row.append(item_xy(f["ele"][0],getattr(record,f["attr"])))
            ws.append(row)
        ffbh = self.mainw.ui.cmb_ffbh.text()
        syy = self.mainw.ui.cmb_syy.text()
        ysry = self.mainw.ui.cmb_ysry.text()
        yqbh = config_json.setting["yqbh"]
        syyqm = self.mainw.ui.cmb_syyqm.text()
        row = ["ffbh&" + ffbh, "", "", "", ""]
        ws.append(row)
        row = ["syy&" + syy, "", "", "", ""]
        ws.append(row)
        row = ["ysry&" + ysry, "", "", "", ""]
        ws.append(row)
        row = ["yqbh&" + yqbh, "", "", "", ""]
        ws.append(row)
        row = ["syyqm&" + syyqm, "", "", "", ""]
        ws.append(row)
        ws.column_dimensions['A'].width = 30.0
        wb.save(filepath)
        self.mainw.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum())                      
if __name__=="__main__":
    file = os.path.join(getpath.getpath(),"..","data","zwk","results.xls")
    config_json.read_setting()
    config_json.setting['database'] = file
    db = MyDb(None)
    objs=db.getDataDays(200)
    for obj in objs:
        print(obj.sampleid)
        for one in obj.items.keys():
            print(one[0]+"_"+one[1],getattr(obj,one[0]+"_"+one[1]))       